#include "network.h"

#include <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>

NetWork::NetWork(QWidget *parent):QMainWindow(parent)
{
    server.listen(QHostAddress::AnyIPv4, 50001);
    connect(&server,&QTcpServer::newConnection,this,&NetWork::new_client);
}

NetWork::~NetWork()
{

}

void NetWork::new_client()
{
    socket = server.nextPendingConnection();
    qDebug()<<"有新的连接";
   //当客户端有数据到达服务器，QTcpSocket对象会发生readyRead信号
   connect(socket, &QTcpSocket::readyRead, this, &NetWork::read_data);
}


void NetWork::read_data()
{

   //获取信号发送者
   QTcpSocket *cSocket = qobject_cast<QTcpSocket*>(sender());
   //开始读取操作
   QString msg = cSocket ->readAll();//读取客户端数据
   qDebug()<<msg;
   QJsonDocument jsonDoc = QJsonDocument::fromJson(msg.toUtf8());
   if (jsonDoc.isNull())
   {
       qDebug() << "Failed to parse JSON";
   }

   // 访问JSON对象中的键值对
    QJsonObject jsonObj = jsonDoc.object();
   // 例如，访问键为"image1"的值
   QString image1Path = jsonObj["image"].toString();
   qDebug() << "Image1 path:" << image1Path;

   QByteArray binaryData = QByteArray::fromBase64(image1Path.toUtf8());
   // 将解码后的二进制数据转换为QImage
   QImage image;
   if (image.loadFromData(binaryData)) {
       // 将QImage转换为QPixmap
     QPixmap pixmapFromImage = QPixmap::fromImage(image);
     bool success = pixmapFromImage.save("D:/share/c++/qtcpp/build-base64-Desktop_Qt_5_14_2_MinGW_64_bit-Debug/newpic.jpg");
     if (!success)
     {
        qDebug() << "Failed to save the image.";
    } else
   {
        qDebug() << "Image saved successfully as" << "mypic.jpg";
    }
   }
   //根据车牌名设置图片名称，并存储在指定路径下
   //把读取到的数据解析判别后转化为正确格式，存放到数据库中
   //参考base64文件把图片编码转化为QPixmap对象
   //QString picname = QString("/zqd/pic/%1.jpg"),arg(QString(name.toUtf8().toBase64()));
   //mmp.save(picname);
}
